var Redis = require('ioredis');

export class RedisService {
    private redis : any;

    constructor() {
        this.redis = new Redis;
    }

    set(key: string, val: any, expr?: number) {
        if (!expr) expr = 24 * 3600;
        if (typeof val == 'object') {
            val = JSON.stringify(val);
        }
        return this.redis.set(key, val, 'EX', expr);
    }

    async get(key: string) {
        try {
            let ret = await this.redis.get(key);
            if (ret[0] == '{' || ret[0] == '[') {
                return JSON.parse(ret);
            }
            else {
                return ret;
            }
        }
        catch (e) {
        }
    }
    

    hset(key : string,field : string,val : any){
        return this.redis.hset(key,field,val);
    }

    del(key : string){

    }

    setWithLock() {

    }
}

export const redisService = new RedisService;